#include <stdio.h>
#include "ohos_init.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"

#include "iot_i2c.h"

#include "cmsis_os2.h"

#define IIC_SDA  0
#define IIC_SCL  1 
#define ADDR 0x27  // 0100111
#define IIC_IDX 1

/*
Command Register
0 Input port 0
1 Input port 1
2 Output port 0
3 Output port 1
4 Polarity Inversion port 0
5 Polarity Inversion port 1
6 Conﬁguration port 0
7 Conﬁguration port 1
*/
#define CMD_CFG0 6
#define CMD_CFG1 7
#define CMD_OUT0 2
#define CMD_OUT1 3

int write_iic(uint8_t* data){
    int ret = IoTI2cWrite(IIC_IDX, (ADDR << 1) | 0x00, data, 3);
    if (ret != 0) {
        printf("===== Error: I2C write config 0 ret = 0x%x! =====\r\n", ret);
    }else{
        printf("i2c send succ %02x %02x %02x \n" , data[0], data[1], data[2]);
    }
    usleep(200*1000);
    return ret;
}

//start 
uint8_t CFG0[] = {CMD_CFG0,0x0,0x0}; //配置为输出
uint8_t CFG1[] = {CMD_CFG1,0x0,0x0}; //配置为输出
uint8_t OUT0[] = {CMD_OUT0,0x00,0xff}; // 输出
uint8_t OUT1[] = {CMD_OUT1,0x00,0xff}; // 输出


void iic(void* args ){
    printf("iic thread running...");
    IoTGpioInit(IIC_SDA);
    IoTGpioInit(IIC_SCL);
    IoTGpioSetFunc(IIC_SDA, IOT_GPIO_FUNC_GPIO_0_I2C1_SDA);
    IoTGpioSetFunc(IIC_SCL, IOT_GPIO_FUNC_GPIO_1_I2C1_SCL);
    IoTI2cInit(IIC_IDX, 400000);     
        
    write_iic(CFG0);
    write_iic(CFG1);

    write_iic(OUT0);
    write_iic(OUT1);

    printf("set finish!\n");
}


APP_FEATURE_INIT(iic);

